package cn.edu.hqu.cst.crj.sharedperences;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button login;
    private EditText username,password;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        login= findViewById(R.id.login);
        username=findViewById(R.id.admin);
        password= findViewById(R.id.pass_word);
        login.setOnClickListener(this);
        initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login:
                showMsg("登录");
                checkAndSaveData();
                break;
        }
    }
    //检查数据并检查数据
    private void checkAndSaveData(){
        String uname=username.getText().toString().trim();
        String upawd=password.getText().toString().trim();

        if(TextUtils.isEmpty(uname)){
            showMsg("请输入用户名");
        }
        else if (TextUtils.isEmpty(upawd)){
            showMsg("请输入密码");
        }
        else{
            boolean flag=SPHelper.saveUserInfo(this,uname,upawd);
            if(flag){
                showMsg("保存数据成功");
            }
            else{
                showMsg("登录失败");
            }
        }
    }

    //显示信息
    private  void  showMsg(String msg){
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    //加载初始化的数据
    public void initData(){
        UserInfo user=SPHelper.getUserInfo(this);
        if (user!=null){
            showMsg("加载初始化数据");
            username.setText(user.name);
            password.setText(user.pawd);
        }
    }

}